#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8

"""
@Copyright © 2017 kouen <kouen@zhoukunwudeMacBook.local>
@License: MIT
@software: Vim
@File Name: CacheMemroy.py
@Create Time: 2017-04-02 15:11

@介绍：
    利用装饰器，缓存数据, 读取数据

    @CacheMemroy("./Cache/EventWrong")
    def fun1(**kwargs):
        pass
"""
import os
import json
import pickle


def getByPickle(reads):
    def decorator(fn):
        def wrapped(**kwargs):
            assert isinstance(reads, dict)

            for name, path in reads.items():
                if os.path.isfile(path) and os.path.getsize(path):
                    with open(path, 'rb') as f:
                        kwargs[name] = pickle.load(f)
                else:
                    kwargs[name] = None
            ret = fn(**kwargs)
            return ret
        return wrapped
    return decorator


def getByJsonLoad(path):
    with open(path, 'r') as f:
        ret = json.load(f)
    return ret


def setByJsonDump(path, obj):
    with open(path, 'w') as f:
        json.dump(obj, f)


def cacheByPickle(paths):  # key: (path, obj())
    def decorator(fn):
        def wrapped(**kwargs):
            for args_key in paths:
                path, obj = paths[args_key]
                if os.path.isfile(path) and os.path.getsize(path):
                    with open(path, 'rb') as f:
                        kwargs[args_key] = pickle.load(f)
                else:
                    kwargs[args_key] = obj()

            ret = fn(**kwargs)
            assert isinstance(ret, dict), u"返回类型必须是dict."
            assert 'ret' in ret, u"返回类型中必须附带ret的key,代表返回类型"

            for k in ret:
                if k in paths and k is not 'ret':
                    path = paths[k][0]
                    with open(path, 'wb') as f:
                        pickle.dump(ret[k], f)
            return ret['ret']
        return wrapped
    return decorator


def unit_json():
    os.system("rm /tmp/1 && touch /tmp/1")
    with open('/tmp/1', 'w') as f:
        json.dump(set(), f)
    with open('/tmp/1', 'r') as f:
        json.load(f)
    os.system("cat /tmp/1")


@cacheByPickle({"cache": ('/tmp/unit_save', int)})
def unit_save(**kwargs):
    if kwargs['cache']:
        kwargs['cache'] += 1
    else:
        kwargs['cache'] = 1
    return {"ret": [], "cache": kwargs['cache']}

if __name__ == "__main__":
    unit_save()
